<template>
  <div class="contract-detail">
    <!-- 视频播放部分 -->
    <div class="detail-section">
      <h2>相关视频</h2>
      <div class="video-container">
        <div class="video-wrapper">
          <video
            ref="videoRef"
            class="contract-video"
            controls
            autoplay
            muted
            crossorigin="anonymous"
            @play="handlePlay"
            @pause="handlePause"
            src="https://storage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4"
          >
            您的浏览器不支持 video 标签。
          </video>
          <div class="video-controls">
            <el-button
              type="primary"
              @click="takeScreenshot"
              :disabled="!isVideoPlaying"
            >
              截图
            </el-button>
          </div>
        </div>

        <div class="preview-wrapper">
          <div class="preview-header">
            <h3>截图预览 ({{ screenshots.length }})</h3>
            <div class="preview-actions">
              <el-button
                type="danger"
                size="small"
                @click="clearAllScreenshots"
                :disabled="!screenshots.length"
              >
                清空
              </el-button>
            </div>
          </div>
          <div class="screenshots-grid" v-if="screenshots.length">
            <div
              v-for="(screenshot, index) in screenshots"
              :key="index"
              class="screenshot-item"
            >
              <div
                class="screenshot-content"
                @click="showFullscreen(screenshot)"
              >
                <img :src="screenshot.url" :alt="`截图 ${index + 1}`" />
                <div class="screenshot-overlay">
                  <div class="screenshot-actions">
                    <el-button
                      type="primary"
                      size="small"
                      circle
                      @click.stop="showFullscreen(screenshot)"
                    >
                      <el-icon><FullScreen /></el-icon>
                    </el-button>
                    <el-button
                      type="success"
                      size="small"
                      circle
                      @click.stop="downloadScreenshot(screenshot)"
                    >
                      <el-icon><Download /></el-icon>
                    </el-button>
                    <el-button
                      type="danger"
                      size="small"
                      circle
                      @click.stop="deleteScreenshot(index)"
                    >
                      <el-icon><Delete /></el-icon>
                    </el-button>
                  </div>
                </div>
              </div>
              <div class="screenshot-info">
                <span>{{ formatTime(screenshot.timestamp) }}</span>
              </div>
            </div>
          </div>
          <div v-else class="empty-screenshots">
            <el-empty description="暂无截图" />
          </div>
        </div>
      </div>

      <!-- 全屏预览弹窗 -->
      <el-dialog
        v-model="isFullscreen"
        fullscreen
        :show-close="true"
        :close-on-click-modal="true"
        class="preview-dialog"
      >
        <div class="fullscreen-preview">
          <img :src="currentScreenshot && currentScreenshot.url" alt="全屏预览" />
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { FullScreen, Download, Delete } from '@element-plus/icons-vue'

export default {
  name: 'ContractDetail',
  components: {
    FullScreen,
    Download,
    Delete
  },
  data() {
    return {
      isVideoPlaying: false,
      isFullscreen: false,
      currentScreenshot: null,
      screenshots: []
    }
  },
  methods: {
    handlePlay() {
      this.isVideoPlaying = true
    },
    handlePause() {
      this.isVideoPlaying = false
    },
    async takeScreenshot() {
      const video = this.$refs.videoRef
      if (!video) return

      try {
        // 检查是否支持HDR截图
        if (window.VideoDecoder) {
          try {
            const blob = await this.takeHDRScreenshot(video)
            const url = URL.createObjectURL(blob)
            const screenshot = {
              url: url,
              timestamp: video.currentTime
            }
            this.screenshots.unshift(screenshot)
          } catch (hdrError) {
            console.warn('HDR截图失败，回退到普通截图:', hdrError)
            // 如果HDR截图失败，回退到普通截图
            this.takeNormalScreenshot(video)
          }
        } else {
          // 如果不支持HDR，使用普通截图
          this.takeNormalScreenshot(video)
        }
      } catch (error) {
        console.error('截图失败:', error)
        alert('截图失败，请重试')
      }
    },
    takeNormalScreenshot(video) {
      const canvas = document.createElement('canvas')
      canvas.width = video.videoWidth
      canvas.height = video.videoHeight

      const ctx = canvas.getContext('2d')
      ctx.drawImage(video, 0, 0, canvas.width, canvas.height)

      try {
        const screenshot = {
          url: canvas.toDataURL('image/png', 1.0), // 使用最高质量
          timestamp: video.currentTime
        }
        this.screenshots.unshift(screenshot)
      } catch (e) {
        console.error('Canvas 导出失败，可能是跨域问题:', e)
        alert('截图失败：视频源不允许跨域访问')
      }
    },
    showFullscreen(screenshot) {
      if (screenshot) {
        this.currentScreenshot = screenshot
        this.isFullscreen = true
      }
    },
    downloadScreenshot(screenshot) {
      if (!screenshot) return

      try {
        const link = document.createElement('a')
        link.href = screenshot.url
        link.download = `screenshot-${this.formatTime(screenshot.timestamp)}.png`
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
      } catch (error) {
        console.error('下载失败:', error)
      }
    },
    deleteScreenshot(index) {
      this.screenshots.splice(index, 1)
    },
    clearAllScreenshots() {
      this.screenshots = []
    },
    formatTime(seconds) {
      const date = new Date(seconds * 1000)
      const hh = date.getUTCHours()
      const mm = date.getUTCMinutes()
      const ss = date.getUTCSeconds().toString().padStart(2, '0')
      if (hh) {
        return `${hh}:${mm.toString().padStart(2, '0')}:${ss}`
      }
      return `${mm}:${ss}`
    },
    async takeHDRScreenshot(videoElement) {
      // 创建视频解码器
      const decoder = new VideoDecoder({
        output: async frame => {
          try {
            // 获取原始HDR帧数据
            const { format, codedWidth, codedHeight, timestamp, colorSpace } = frame;
            
            // 创建支持HDR的canvas
            const canvas = document.createElement('canvas');
            const ctx = canvas.getContext('2d', {
              colorSpace: colorSpace || 'display-p3', // 使用视频原始色彩空间
              willReadFrequently: true
            });
            
            // 设置canvas尺寸
            canvas.width = codedWidth;
            canvas.height = codedHeight;
            
            // 将HDR帧绘制到canvas
            ctx.drawImage(frame, 0, 0);
            
            // 导出为支持HDR的格式
            const blob = await new Promise(resolve => {
              canvas.toBlob(resolve, 'image/png', 1.0, {
                colorSpace: colorSpace || 'display-p3',
                // 保持HDR元数据
                transferFunction: colorSpace?.transfer || 'pq', // 默认使用PQ
                matrixCoefficients: colorSpace?.matrix || 'bt2020nc',
                primaries: colorSpace?.primaries || 'bt2020'
              });
            });
            
            // 清理
            frame.close();
            decoder.close();
            
            return blob;
          } catch (error) {
            console.error('HDR帧处理错误:', error);
            throw error;
          }
        },
        error: error => {
          console.error('解码错误:', error);
          throw error;
        }
      });

      try {
        // 获取视频轨道
        const videoTrack = videoElement.captureStream().getVideoTracks()[0];
        if (!videoTrack) {
          throw new Error('无法获取视频轨道');
        }

        // 配置解码器
        await decoder.configure({
          codec: videoTrack.getSettings().codec || 'vp09.00.10.08',
          optimizeForLatency: true,
          hardwareAcceleration: 'prefer-hardware',
          // 保持原始色彩空间
          colorSpace: {
            transfer: 'pq', // 或 'hlg'
            matrix: 'bt2020nc',
            primaries: 'bt2020'
          }
        });

        // 创建视频处理管道
        const processor = new MediaStreamTrackProcessor({ track: videoTrack });
        const reader = processor.readable.getReader();

        // 读取并处理视频帧
        while (true) {
          const { done, value } = await reader.read();
          if (done) break;
          
          if (value) {
            await decoder.decode(value);
            value.close();
          }
        }
      } catch (error) {
        console.error('HDR截图处理错误:', error);
        throw error;
      }
    }
  }
}
</script>

<style scoped>
.contract-detail {
  padding: 32px;
  background-color: #f6f8fa;
  min-height: 100vh;
}

.detail-section {
  background-color: #fff;
  border-radius: 12px;
  padding: 32px;
  margin-bottom: 24px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
}

.detail-section h2 {
  margin: 0 0 32px 0;
  font-size: 20px;
  font-weight: 600;
  color: #1a1a1a;
  position: relative;
  padding-left: 16px;
}

.detail-section h2::before {
  content: '';
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 4px;
  height: 20px;
  background: #409eff;
  border-radius: 2px;
}

.video-container {
  display: flex;
  gap: 32px;
  max-width: 1400px;
  margin: 0 auto;
}

.video-wrapper {
  flex: 1.2;
  min-width: 0;
  background: #fff;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.06);
}

.contract-video {
  width: 100%;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.preview-wrapper {
  flex: 1;
  min-width: 0;
  background: #fff;
  border-radius: 12px;
  padding: 24px;
  max-height: 700px;
  overflow-y: auto;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.06);
}

.preview-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #ebeef5;
}

.preview-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #1a1a1a;
}

.screenshots-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
  gap: 20px;
  margin-top: 20px;
}

.screenshot-item {
  position: relative;
  border-radius: 8px;
  overflow: hidden;
  background: #fff;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  transition: transform 0.3s ease;
}

.screenshot-item:hover {
  transform: translateY(-4px);
}

.screenshot-content {
  position: relative;
  cursor: pointer;
  aspect-ratio: 16/9;
  overflow: hidden;
}

.screenshot-content img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.4s ease;
}

.screenshot-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.6);
  display: flex;
  justify-content: center;
  align-items: center;
  opacity: 0;
  transition: opacity 0.3s ease;
  backdrop-filter: blur(2px);
}

.screenshot-content:hover .screenshot-overlay {
  opacity: 1;
}

.screenshot-content:hover img {
  transform: scale(1.08);
}

.screenshot-actions {
  display: flex;
  gap: 12px;
  z-index: 2;
}

.screenshot-info {
  padding: 12px;
  font-size: 13px;
  color: #606266;
  text-align: center;
  background: #f8f9fa;
  border-top: 1px solid #ebeef5;
}

.empty-screenshots {
  padding: 48px 0;
}

.video-controls {
  margin-top: 24px;
  text-align: center;
}

:deep(.el-button) {
  border-radius: 6px;
  font-weight: 500;
  transition: all 0.3s ease;
}

:deep(.el-button--primary) {
  background: #409eff;
  border-color: #409eff;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.2);
}

:deep(.el-button--primary:hover) {
  background: #66b1ff;
  border-color: #66b1ff;
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
}

:deep(.el-button--danger) {
  background: #f56c6c;
  border-color: #f56c6c;
  box-shadow: 0 2px 8px rgba(245, 108, 108, 0.2);
}

:deep(.el-button--danger:hover) {
  background: #f78989;
  border-color: #f78989;
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(245, 108, 108, 0.3);
}

.fullscreen-preview {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  background: rgba(0, 0, 0, 0.95);
}

.fullscreen-preview img {
  max-width: 95%;
  max-height: 95%;
  object-fit: contain;
  border-radius: 8px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.2);
}

:deep(.preview-dialog .el-dialog__body) {
  padding: 0;
  height: 100%;
}

:deep(.el-dialog) {
  border-radius: 12px;
  overflow: hidden;
}

:deep(.el-dialog__header) {
  padding: 20px;
  margin: 0;
  border-bottom: 1px solid #ebeef5;
}

:deep(.el-dialog__title) {
  font-weight: 600;
  color: #1a1a1a;
}

:deep(.el-dialog__headerbtn) {
  top: 20px;
  right: 20px;
}

:deep(.el-dialog__headerbtn .el-dialog__close) {
  font-size: 20px;
  color: #909399;
}

:deep(.el-dialog__headerbtn:hover .el-dialog__close) {
  color: #409eff;
}
</style> 